package com.netty.client.udp;

import com.netty.constant.Constants;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author zl
 * @version 1.0
 * @date 2021/9/24 16:17
 */
public class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private ImUdpClientHandler imUdpClientHandler;

    public UdpClientHandler(ImUdpClientHandler imUdpClientHandler) {
        this.imUdpClientHandler = imUdpClientHandler;
    }

    //客户端去和服务端连接成功时触发
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info(">>>>>>>>>>>>>>>>>>>>>>channel链接成功<<<<<<<<<<<<<<<<<<<<<<");
        imUdpClientHandler.channelActive(ctx);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        logger.info(">>>>>>>>>>>>>>>>>>>>>>channel注册了<<<<<<<<<<<<<<<<<<<<<<");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.info(">>>>>>>>>>>>>>>>>>>>>>channel 捕获到异常了，关闭了{}<<<<<<<<<<<<<<<<<<<<<<", cause);
        super.exceptionCaught(ctx, cause);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket) throws Exception {
        Constants.executorService.submit(new Runnable() {
            @Override
            public void run() {
                imUdpClientHandler.channelRead0(channelHandlerContext.channel(), datagramPacket);
            }
        });
    }
}
